#include "qprojectloader.h"

#include "qupdatewidget.h"

#include "../../libs/runningLib/qrunningcore.h"
#include "../libs/baselib/qupdatemanager.h"
#include "../libs/baselib/qabstractupdater.h"
#include "../../libs/sharedLib/qprojectresource.h"

#include <QFile>
#include <QApplication>
#include <QSettings>
#include <QUuid>
#include <QProcess>

QProjectLoader::QProjectLoader():
    m_runningWindow(NULL),
    m_updaterManager(new BASELIB::QUpdateManager(this))
{
    init();
    m_runningWindow=new RUNNINGLIB::QRunningWindow(m_projectPath);
    m_updateWidget=new QUpdateWidget;
    m_updateWidget->setVisible(false);

    connect(m_updaterManager,SIGNAL(updateFinish()),this,SLOT(updateFinish()));
}

QProjectLoader::~QProjectLoader()
{
    if(m_runningWindow!=NULL)
    {
        delete m_runningWindow;
        m_runningWindow=NULL;
    }
    if(m_updateWidget!=NULL)
    {
        delete m_updateWidget;
        m_updateWidget=NULL;
    }
    delete m_updaterManager;
}

void QProjectLoader::init()
{

    QSettings s(qApp->applicationDirPath()+"/config.ini",QSettings::IniFormat,this);
    m_projectPath=s.value("project/path").toString();
    if(m_projectPath=="")
    {
        m_projectPath=qApp->applicationDirPath()+"/project";
    }
    m_uuid=s.value("project/uuid").toString();
    if(m_uuid=="")
    {
        m_uuid=QUuid::createUuid().toString();
        s.setValue("project/uuid",m_uuid);
    }
}

void QProjectLoader::run()
{
    m_updaterManager->loadUpdatePlugin();
    m_updaterManager->updaterStart(m_uuid);
    if(m_runningWindow!=NULL)
    {
        SHAREDLIB::QProjectResource::resource()->load(m_projectPath);
        if(m_runningWindow->run())
        {
            return;
        }
        SHAREDLIB::QProjectResource::resource()->clear();
    }
    delete m_runningWindow;
    m_runningWindow=NULL;
    m_updateWidget->setVisible(true);
}

void QProjectLoader::updateFinish()
{
    QProcess::startDetached(QApplication::applicationDirPath()+"/softUpdate.exe");
    if(m_runningWindow!=NULL)
    {
        delete m_runningWindow;
        m_runningWindow=NULL;
    }
    if(m_updateWidget!=NULL)
    {
        delete m_updateWidget;
        m_updateWidget=NULL;
    }
}
